<?php

// TODO check throwing Headers Sent Exception

/**
 * File Description
 * 
 * Kao: PHP Web Framework <http://kao.byhuy.com/>.
 * Copyright 2008, Huy Nguyen <http://www.byhuy.com/>.
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 * 
 */

class Kao_Response
{
    /**
     * List of all known HTTP response codes
     *
     * "Borrowed" from Zend Framework (Zend_Http_Response)
     * @var array
     */
    protected static $_messages = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',

        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',  // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',

        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',

        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );
    
    /**
     * Default response code
     */
    protected $_responseCode = 200;
    
    /**
     * Custom response message
     */
    protected $_customResponseMessage = null;
    
    /**
     * Cookie
     */
    protected $_cookies = array();
    
    /**
     * Headers (except Cookies)
     */
    protected $_headers = array();
    
    
    /**
     * Output
     */
    protected $_output = '';
    
    
    /**
     * Sets response code
     * 
     * @param int $code
     * @return Kao_Response
     */
    public function setReponseCode($code)
    {
        $this->_responseCode = $code;
        return $this;
    }
    
    /**
     * Set custom response message
     * 
     * @param string $message
     * @return Kao_Response
     */
    public function setCustomResponseMessage($message)
    {
        $this->_customResponseMessage = $message;
        return $this;
    }
    
    /**
     * Send HTTP response code
     * 
     * @return bool
     */
    public function sendResponseCode()
    {
        if (!$this->canSendHeaders())
        {
            return false;
        }
        
        $headerMessage = (string) $this->_responseCode;
        
        if (null != $this->_customResponseMessage)
        {
            $headerMessage .= ' ' . $this->_customResponseMessage;
        }
        elseif (isset(self::$_messages[$this->_responseCode]))
        {
            $headerMessage .= ' ' . self::$_messages[$this->_responseCode];
        }
        header('HTTP/1.x ' . $headerMessage);
        return true;
    }
    
    /**
     * Set cookie
     * 
     * @param string $name
     * @param string $value
     * @param string $expire
     * @param string $path
     * @param string $domain
     * @param bool $secure
     * @param bool $httponly
     * @return Kao_Response
     */
    public function setCookie($name, $value = '', $expire = null, $path = null, $domain = null, $secure = false, $httponly = false)
    {
        $this->_cookies[$name] = array(
            'value'    => $value,
            'expire'   => $expire,
            'path'     => $path,
            'domain'   => $domain,
            'secure'   => $secure,
            'httponly' => $httponly,
        );
        return $this;
    }
    
    /**
     * Sends cookies to client.
     */
    public function sendCookies()
    {
        foreach ($this->_cookies as $name => $jar)
        {
            setcookie($name, $jar['value'], $jar['expire'], $jar['path'], $jar['domain'], $jar['secure'], $jar['httponly']);
        }
    }
    
    /**
     * Clears set cookies
     * 
     * @return Kao_Response
     */
    public function clearCookies()
    {
        $this->_cookies = array();
        return $this;
    }
    
    /**
     * Get cookies data
     * 
     * @return array
     */
    public function getCookies()
    {
        return $this->_cookies;
    }
    
    /**
     * Add a header element
     * 
     * @param string $header
     * @return Kao_Response
     */
    public function setHeader($header)
    {
        $this->_headers[] = $header;
        return $this;
    }
    
    /**
     * Returns headers data
     * 
     * @return array
     */
    public function getHeaders()
    {
        return $this->_headers;
    }
    
    /**
     * Clear headers data
     * 
     * @return Kao_Response
     */
    public function clearHeaders()
    {
        $this->_headers = array();
        return $this;
    }
    
    /**
     * Can send header or not?
     * If the output was already sent, this function return false
     * 
     * @return bool
     */
    public function canSendHeaders()
    {
        return !headers_sent();
    }
    
    /**
     * Send headers to clients
     * 
     * @return Kao_Response
     */
    public function sendHeaders()
    {
        foreach ($this->_headers as $header)
        {
            header($header);
        }
        return $this;
    }
    
    /**
     * Set output
     * 
     * @param string $output
     * @param bool $join If true, the $output will join with the current output string
     * @return Kao_Response
     */
    public function setOutput($output, $join = false)
    {
        if (!$join)
        {
            $this->_output = $output;
        }
        else 
        {
            $this->_output .= $output;
        }
        return $this;
    }
    
    /**
     * Send output to client
     * 
     * @return void
     */
    public function sendOutput()
    {
        if ($this->canSendHeaders())
        {
            $this->setReponseCode();
            $this->sendHeaders();
            $this->sendCookies();
        }
        echo $this->_output;
    }
}


